<template>
	<view>
		<uni-drawer :visible="visibleDrawer" :hideNoAnimate="showBackButton" mode="right" @close="closeDrawer()">
			<!-- #ifdef APP-PLUS -->
			<view class="iconfont icon-guanbi" v-if="showBackButton" @tap="closeDrawer()"></view>
			<!-- #endif -->
			<scroll-view class="drawer-list" scroll-y :style="{ height: drawerHeight, 'padding-top': fixTop }">
				<block v-for="(item, index) in menuList" :key="index">
					<!-- 单选、多选  isMutiple是否支持多选-->
					<view v-if="item.type === 'custom' && item.detailList.length">
						<view class="drawer-list-title flex justify-between">
							<view>{{ item.title }}</view>
							<text v-if="item.detailList.length > showLenght" @tap="showMore(index)">{{ item.showMoreList ? '收起' : '更多' }}</text>
						</view>
						<view class="draer-list-con">
							<template v-if="!item.showMoreList">
								<text
									:style="{ background: textItem.isSelected ? color : '', color: textItem.isSelected ? '#ffffff' : '' }"
									v-if="idx < showLenght"
									v-for="(textItem, idx) in item.detailList"
									:key="idx"
									:class="textItem.isSelected ? 'on' : ''"
									@tap="itemTap(idx, item.detailList, item.key, item.isMutiple)"
								>
									{{ textItem.title }}
								</text>
							</template>
							<template v-else>
								<text
									:style="{ background: textItem.isSelected ? color : '', color: textItem.isSelected ? '#ffffff' : '' }"
									v-for="(textItem, idx) in item.detailList"
									:key="idx"
									:class="textItem.isSelected ? 'on' : ''"
									@tap="itemTap(idx, item.detailList, item.key, item.isMutiple)"
								>
									{{ textItem.title }}
								</text>
							</template>
						</view>
					</view>

					<!-- 单输入框 -->
					<view v-if="item.type === 'singleinput'">
						<view class="drawer-list-title flex justify-between">
							<view>{{ item.title }}</view>
						</view>
						<view class="dateContent">
							<view><input class="m-input" clearable v-model="result[item.key]" :placeholder="item.placeholder || '输入会员ID进行搜索'" /></view>
						</view>
					</view>
				</block>

				<view>
					<view @click="addshow = true" class="space-between center" style="margin-top: 20rpx;">
						<view class="tkwz">所在地</view>
						<view class="inputi-name-im-c">
							<pick-regions :defaultRegion="defaultRegionCode" @getRegion="handleGetRegion">
								<view v-if="carr" class="inputi-name" style="width: 400rpx;text-align: right;">{{ carr }}</view>
								<view v-else class="inputi-name-ww">选择省市区</view>
							</pick-regions>
						</view>
					</view>
				
				</view>
				<u-divider ></u-divider>
				<!-- <view>
					<view @click="tzshow = true" class="space-between center" style="margin-top: 20rpx;">
						<view class="tkwz">体重(kg)</view>
						<view class=" center">
							<view style="color: #686363;">{{tzvalue}}</view>
							<u-icon name="arrow-right" color="#686363" size="16"></u-icon>
						</view>
					</view>
					<view>
						<u-keyboard @backspace="backspacetz" @change="tzaj" @confirm="tzqd" @cancel="tzqx" ref="uKeyboard" mode="number" tips="体重(kg)" :show="tzshow"></u-keyboard>
					</view>
				</view> -->
				
				<u-divider ></u-divider>
				
				<view>
					<view @click="xlshow = true" class="space-between center" style="margin-top: 20rpx;">
						<view class="tkwz">学历</view>
						<view class=" center">
							<view style="color: #686363;">{{xlvalue}}</view>
							<u-icon name="arrow-right" color="#686363" size="16"></u-icon>
						</view>
					</view>
					<view>
						<u-picker @confirm="xlqd" @cancel="xlqx" :show="xlshow" :columns="xlcolumns"></u-picker>
					</view>
				</view>
				
				<u-divider ></u-divider>
				<view>
					<view @click="srshow = true" class="space-between center" style="margin-top: 20rpx;">
						<view class="tkwz">月收入</view>
						<view class=" center">
							<view style="color: #686363;">{{srvalue}}</view>
							<u-icon name="arrow-right" color="#686363" size="16"></u-icon>
						</view>
					</view>
					<view>
						<u-keyboard @backspace="srbackspace" @change="sraj" @confirm="srqd" @cancel="srqx" ref="uKeyboard" mode="number" tips="月收入" :show="srshow"></u-keyboard>
					</view>
				</view>
				
				
			</scroll-view>

			<view class="filter-content-footer flex justify-center">
				<!-- #ifdef APP-PLUS-->
				<view v-if="showBackButton" class="filter-content-footer-item" :style="{ color: '#ccc', border: '1rpx solid #ccc' }" @tap="closeDrawer()"><text>返回</text></view>
				<!-- #endif -->
				<view class="filter-content-footer-item" :style="{ color, border: `1rpx solid ${color}` }" @tap="resetClick"><text>重置</text></view>
				<view class="filter-content-footer-item" :style="{ background: color }" @tap="sureClick"><text>确认</text></view>
			</view>
		</uni-drawer>
		<mx-date-picker :show="showPicker" :color="color" :type="dateType" :value="dateValue" :show-tips="true" :show-seconds="true" @confirm="onSelected" @cancel="onSelected" />
	</view>
</template>

<script>
/***
 * 筛选组件，当前支持多选、单选
 * item.type (custom 单选、多选、rangetime 时间范围带时分秒、range 时间范围不带时分秒、rangenumber 数字范围)
 * item.isMutiple 是否支持多选
 * 筛选后返回格式{"listName1":[value,value](多选),"listName2":"value"（单选）,...}
 * rangenumber形式-可能为["",1]或[1,""]表示只有一个最大值或最小值
 ***/
import uniDrawer from '@/components/uni-drawer/uni-drawer.vue';
import MxDatePicker from '@/components/mx-datepicker/mx-datepicker.vue';
export default {
	props: {
		list: {
			required: true,
			type: Array,
			default() {
				return [];
			}
		},
		color: {
			type: String,
			default: '#4D7BFE'
		},
		defaultValue: {
			//若有默认值则触发sureClick
			type: Object,
			default() {
				return {};
			}
		},
		showBackButton: {
			type: Boolean,
			default: false
		}
	},
	watch: {
		list: {
			handler(val) {
				this.menuList = JSON.parse(JSON.stringify(val));
				this.resetResult();
				this.defaultValueFun();
			},
			deep: true // 可以深度检测到 obj 对象的属性值的变化
		}
	},
	components: {
		uniDrawer,
		MxDatePicker
	},
	beforeCreate() {
		Object.isEmpty = (object, except = []) => {
			if (!object) {
				return false;
			}
			for (let key in object) {
				if (except && except.includes(key)) {
					continue;
				}
				if (object.hasOwnProperty(key)) {
					return false;
				}
			}
			return true;
		};
		Date.prototype.Format = function(fmt) {
			//author: meizz
			var o = {
				'M+': this.getMonth() + 1, //月份
				'd+': this.getDate(), //日
				'h+': this.getHours(), //小时
				'm+': this.getMinutes(), //分
				's+': this.getSeconds(), //秒
				'q+': Math.floor((this.getMonth() + 3) / 3), //季度
				S: this.getMilliseconds() //毫秒
			};
			if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
			for (var k in o) if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
			return fmt;
		};
		String.prototype.replaceAll = function(oldValue, newValue) {
			return this.toString().replace(new RegExp(oldValue, 'gm'), newValue);
		};
	},
	created() {
		this.menuList = JSON.parse(JSON.stringify(this.list));
		this.resetResult();
		uni.getSystemInfo({
			success: res => {
				let windowHeight = res.windowHeight;
				// #ifdef H5
				if (!(this.$IsWeixin || this.$IsAlipay || this.$IsCloudPay)) {
					let thirdApp = getApp().globalData.options?.thirdApp;
					if (thirdApp && thirdApp.hideNavBar) {
						// 第三方App使用App原生导航栏
					} else {
						this.fixTop = (res.statusBarHeight || 0) + 'px';
					}
				}
				windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || res.windowHeight;
				// #endif
				this.drawerHeight = windowHeight - uni.upx2px(120) + 'px';
				// uni.showModal({
				// 	content: `model: ${res.model}`,
				// })
			}
		});
	},
	mounted() {
		this.defaultValueFun();
	},
	computed: {},
	data() {
		return {
			addshow:false,
			carr: '', //常住地
			province_id: '',
			city_id: '',
			area_id: '',
			province: '',
			city: '',
			area: '',
			srshow:false,//月收入
			srvalue:'',//月收入值
			xlshow:false,//学历
			xlvalue:'',//学历值
			tzvalue:'',//体重值
			tzshow:false,//体重
			xlcolumns: [['博士', '硕士', '本科', '大专', '高中', '初中']],
			menuList: [],
			visibleDrawer: false,
			menuKey: 1,
			showLenght: 6,
			drawerHeight: '500px',
			selectDetailList: [],
			result: {},
			showPicker: false,
			dateType: 'rangetime',
			dateValue: '',
			fixTop: '0px'
		};
	},

	methods: {
		
		// 获取选择的地区
		handleGetRegion(region) {
			this.province = region[0].name;
			this.city = region[1].name;
			this.area = region[2].name;
		
			this.province_id = region[0].code;
			this.city_id = region[1].code;
			this.area_id = region[2].code;
			this.carr = this.province + '/' + this.city + '/' + this.area;
			console.log('region', region);
		},
	
		
		// 体重取消
		tzqx() {
			this.tzshow = false;
		},
		// 体重确定
		tzqd() {
			this.tzshow = false;
		},
		// 体重按建
		tzaj(val){
			this.tzvalue += val;
			console.log(this.tzvalue);
		},
		//体重退格
		backspacetz(){
			// 删除value的最后一个字符
		if(this.tzvalue.length) this.tzvalue = this.tzvalue.substr(0, this.tzvalue.length - 1);
		console.log(this.tzvalue);
		},
		
		
		// 学历取消
		xlqx() {
			this.xlshow = false;
		},
		// 学历确定
		xlqd(e) {
			 console.log('confirm', e.value[0])
			 this.xlvalue = e.value[0]
			this.xlshow = false;
		},
		
		
		// 月收入确定
		srqd() {
			this.srshow = false;
		},
		
		//月收入取消
		srqx() {
			this.srshow = false;
		},
		
		// 月收入按建
		sraj(val){
			this.srvalue += val;
			console.log(this.srvalue);
		},
		//月收入退格
		srbackspace(){
			// 删除value的最后一个字符
		if(this.srvalue.length) this.srvalue = this.srvalue.substr(0, this.srvalue.length - 1);
		console.log(this.srvalue);
		},
		
		defaultValueFun() {
			//如果有默认值，则赋值后调用sureClick通知父组件更新
			if (!Object.isEmpty(this.defaultValue)) {
				const value = this.defaultValue;
				const list = JSON.parse(JSON.stringify(this.menuList));
				for (let key in value) {
					for (let i = 0; i < list.length; i++) {
						if (list[i].key === key) {
							if (list[i].type === 'custom') {
								list[i].detailList.map((item, index) => {
									if (Array.isArray(value[key]) && value[key].indexOf(item.value) > -1) {
										item.isSelected = true;
									} else if (value[key] == item.value) {
										item.isSelected = true;
									}
									return item;
								});
								continue;
							}
							if (
								list[i].type === 'range' ||
								list[i].type === 'rangetime' ||
								(list[i].type === 'rangenumber' && Array.isArray(value[key]) && value[key].length === 2)
							) {
								this.result[key] = value[key];
								this.result[list[i].minName || list[i].key + 'Min'] = value[key][0];
								this.result[list[i].maxName || list[i].key + 'Max'] = value[key][1];
								continue;
							}
							if (list[i].type === 'date' || (list[i].type === 'singleinput' && value[key])) {
								this.result[key] = value[key];
								continue;
							}
						}
					}
				}
				if (this.defaultRefeshTimer) {
					clearTimeout(this.defaultRefesh·Timer);
				}
				this.defaultRefeshTimer = setTimeout(() => {
					console.log('筛选默认值触发');
					this.menuList = list;
					this.sureClick();
				}, 200);
			}
		},

		resetResult() {
			this.result = this.commonResultObj();
		},
		commonResultObj() {
			let obj = {};
			this.menuList.map(item => {
				switch (item.type) {
					case 'custom':
						item.isMutiple ? (obj[item.key] = []) : (obj[item.key] = '');
						item.detailList.forEach(dListItem => {
							dListItem.isSelected = dListItem.isSelected || false;
						});
						break;
					case 'range':
					case 'rangetime':
					case 'rangenumber':
						this.result[item.key] = [];
						this.result[item.minName || item.key + 'Min'] = '';
						this.result[item.maxName || item.key + 'Max'] = '';
						break;
					default:
						obj[item.key] = '';
				}
			});
			return obj;
		},
		//筛选项选中或取消
		itemTap(index, list, key, isMutiple) {
			if (isMutiple == true) {
				list[index].isSelected = !list[index].isSelected;
				if (list[index].isSelected) {
					this.result[key].push(list[index].value);
				} else {
					list[index].isSelected = false;
					var idx = this.result[key].indexOf(list[index].value);
					this.result[key].splice(idx, 1);
				}
			} else {
				this.result[key] = list[index].isSelected ? '' : list[index].value;
				for (let i = 0; i < list.length; i++) {
					if (index == i && !list[i].isSelected) {
						list[i].isSelected = true;
					} else {
						list[i].isSelected = false;
					}
				}
			}

			// #ifdef H5 || APP-PLUS
			this.$forceUpdate();
			// #endif
		},

		sureClick() {
			this.menuList.forEach(menu => {
				let list = menu.detailList || [];
				if (menu.type == 'custom' && list.length > 0) {
					let selectedValueList = [];
					list.forEach(item => {
						if (item.isSelected) {
							selectedValueList.push(item.value);
						}
					});

					if (menu.isMutiple == true) {
						this.result[menu.key] = selectedValueList;
					} else {
						this.result[menu.key] = selectedValueList[0] || '';
					}
				}
			});

			let str_result = {};
			let hasChoose = false;
			for (let key in this.result) {
				if (typeof this.result[key] == 'object') {
					str_result[key] = this.result[key].join(',');
					if (!hasChoose) {
						hasChoose = this.result[key].join(',') !== '' ? true : false;
					}
				} else {
					str_result[key] = this.result[key];
					if (!hasChoose) {
						hasChoose = this.result[key] !== '' ? true : false;
					}
				}
			}

			this.$emit('result', {
				education:this.xlvalue,//学历
				profit:this.srvalue,//月收入
				province:this.province,
				city:this.city,
				area:this.area,
				str_result: str_result,
				result: this.result,
				hasChoose: hasChoose,
				visibleDrawer: false
			});
		},
		resetClick() {
			this.xlvalue = '';
			this.srvalue = '';
			this.province = '';
			this.city = '';
			this.area = '';
			this.tzvalue = '';
			this.carr = '';
			
			this.minNumber = '';
			this.minNumber = '';
			for (let key in this.result) {
				if (typeof this.result[key] === 'object') {
					this.result[key] = [];
				} else {
					this.result[key] = '';
				}
			}
			for (let i = 0; i < this.menuList.length; i++) {
				if (this.menuList[i].type === 'custom') {
					for (let j = 0; j < this.menuList[i].detailList.length; j++) {
						this.menuList[i].detailList[j].isSelected = false;
					}
				}
			}
			// #ifdef H5 || APP-PLUS
			this.$forceUpdate();
			// #endif
		},
		closeDrawer() {
			this.visibleDrawer = false;
			// #ifdef APP-PLUS
			this.$emit('result', {
				type: 1
			});
			// #endif
		},

		showMore(index) {
			this.menuList[index].showMoreList = !this.menuList[index].showMoreList;
			++this.menuKey;
			// #ifdef H5 || APP-NVUE
			this.$forceUpdate();
			// #endif
		},

		onShowDatePicker(type, key, item) {
			//显示
			this.dateType = type;
			this.dateValue = this.result[key] || '';
			this.showPicker = true;
			this.tempKey = key;
			this.item = item;
		},

		onSelected(e, key) {
			//选择
			this.showPicker = false;
			if (e) {
				this.result[this.tempKey] = e.value;
				if (e.value && e.value.length && this.item && this.item.type !== 'date') {
					let item = this.item;
					this.result[item.minName || item.key + 'Min'] = e.value[0].replaceAll('/', '-');
					this.result[item.maxName || item.key + 'Max'] = e.value[1].replaceAll('/', '-');
				}
				//选择的值
				console.log('value => ' + e.value);
				//原始的Date对象
				console.log('date => ' + e.date);
			}
		},

		numberInputBlur(item) {
			let minNumber = this.result[item.minName || item.key + 'Min'];
			let maxNumber = this.result[item.maxName || item.key + 'Max'];
			if (minNumber != '' && maxNumber != '' && parseFloat(minNumber) > parseFloat(maxNumber)) {
				let temp = minNumber;
				this.result[item.minName || item.key + 'Min'] = maxNumber;
				this.result[item.maxName || item.key + 'Max'] = temp;
			}
			this.result[item.key] = [];
			this.result[item.key].push(minNumber && parseFloat(minNumber));
			this.result[item.key].push(maxNumber && parseFloat(maxNumber));
		}
	}
};
</script>

<style lang="scss" scoped>
.uni-drawer__content {
	width: 320px !important;
}
.flex {
	display: flex;
}

.justify-between {
	justify-content: space-between;
}

view,
scroll-view,
swiper,
button,
input,
textarea,
label,
navigator,
image {
	box-sizing: border-box;
}

/* 筛选样式 */
.drawer-list {
	padding: 0 20rpx;
	font-size: 26rpx;
}

input {
	font-size: 26rpx;
}

.drawer-list .drawer-list-title {
	font-size: 34rpx;
	font-weight: 400;
	line-height: 48rpx;
	margin: 38rpx 0 18rpx;
	color: rgba(34, 34, 34, 1);
}

.drawer-list .drawer-list-title > text {
	font-size: 26rpx;
	color: #666666;
}

.drawer-list .draer-list-con > text {
	background: rgba(93, 92, 254, 0.1);
	border-radius: 8px;
	color: #666666;
	font-size: 28rpx;
	padding: 10rpx 28rpx;
	margin: 10rpx 10rpx 10rpx 0;
	display: inline-block;
}

.filter-content-footer-item {
	flex: 1;
	height: 72rpx;
	line-height: 72rpx;
	text-align: center;
	border-radius: 8rpx;
	margin: 14rpx;
	color: #ffffff;
}

.picker {
	z-index: 99999 !important;
}

.dateContent {
	& > view {
		background: rgba(244, 244, 244, 1);
		border-radius: 8rpx;
		width: 100%;
		height: 64rpx;
		line-height: 64rpx;
		margin-bottom: 12rpx;
		padding: 0 12rpx;
	}
}

.rangenumber-content {
	& > text {
		display: inline-block;
		width: 10%;
		text-align: center;
		height: 64rpx;
		line-height: 64rpx;
	}

	.rangenumber-input {
		width: 45%;
		display: inline-block;
		padding: 0 12rpx;
	}
}

.m-input {
	height: 64rpx;
	line-height: 64rpx;
}

::v-deep .picker {
	z-index: 999;
}
.icon-guanbi {
	position: fixed;
	top: 40rpx;
	right: 40rpx;
	z-index: 1000;
}
.tkwz{
	font-size: 28rpx;
	font-family: PingFang;
	font-weight: bold;
	color: #333333;
}
</style>
